package com.banciyuan.bcywebview.biz.main.daily;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoreApi;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.TagDetail;

/**
 * Created by squall on 2016/9/2.
 */
public class DailyAllFragment extends BaseLazyContainerFragment {

    public static final int TYPE_CIRCLE = 3;
    private RequestQueue queue;

    private PullToRefreshListView mRefreash;
    private ListView mListView;
    private ProgressbarHelper mProgressbarHelper;

    private int page = 1;
    private boolean is_load = false;
    private boolean is_end = false;

    private List<TagDetail> tlist = new ArrayList<>();
    private DailyTagsAdapter dailyTagsAdapter;

    private int index = 1;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View viewroot = inflater.inflate(R.layout.daily_all_fragment, null);
        initArgs();
        initProgressbar(viewroot);
        initUi(viewroot);
        initAction();
        return viewroot;
    }

    @Override
    protected void initArgs() {
        queue = VolleyQueue.getRquest(getActivity());
        index = getArguments().getInt(gotoUtil.INTENT_VALUE_ONE);
    }

    @Override
    public void fetchData() {
        getData();
    }

    @Override
    protected void initData() {
        if (is_load) return;
        is_load = true;
        getAllCircleTags();
    }

    private void getData() {
        is_load = false;
        is_end = false;
        page = 1;
        initData();
    }

    @Override
    protected void initProgressbar(View rootview) {
        View mProgressbarView = rootview.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                getData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initAction() {
        mRefreash.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!is_end && !is_load && index != 0) {
                    page++;
                    initData();
                }
            }
        });

        mRefreash.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                getData();
            }
        });
    }

    private void getAllCircleTags() {
        String url = HttpUtils.BASE_URL + CoreApi.getAllHotCore();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(page)));
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String result = jsonObject.getString(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        List<TagDetail> templist = gson.fromJson(result, new TypeToken<List<TagDetail>>() {
                        }.getType());
                        for (TagDetail cir : templist) {
                            cir.setType("work");
                        }
                        renderData(templist);
                    } catch (Exception e) {
                        onLoadingError();
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                onLoadingError();
            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam param = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        queue.add(param);
    }

    private void onLoadingError() {
        mProgressbarHelper.onFailed();
        mRefreash.onRefreshComplete();
        is_load = false;
    }

    @Override
    protected void initUi(View rootview) {
        mRefreash = (PullToRefreshListView) rootview.findViewById(R.id.listView);
        mListView = mRefreash.getRefreshableView();

        AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, UIUtils.dip2px(8, getActivity()));
        View view = new View(getActivity());
        view.setLayoutParams(layoutParams);
        mListView.addHeaderView(view);
    }

    private void renderData(List<TagDetail> templist) {
        if (page == 1) {
            tlist.clear();
        }
        if (templist.size() == 0) {
            is_end = true;
        }
        tlist.addAll(templist);
        if (dailyTagsAdapter == null) {
            dailyTagsAdapter = new DailyTagsAdapter(tlist, getActivity());
            mListView.setAdapter(dailyTagsAdapter);
            dailyTagsAdapter.setMlistView(mListView);
        } else {
            dailyTagsAdapter.notifyDataSetChanged();
        }
        mRefreash.onRefreshComplete();
        mProgressbarHelper.onSuccess();
        is_load = false;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
    }


}
